package authenum

import (
	"fmt"
	"yunj/pkg/yunj/core/enum"
)

// 定义权限类型常量
const (
	// 常规
	TYPE_NORMAL uint8 = 0

	// 侧边栏菜单
	TYPE_SIDEBAR_MENU uint8 = 11

	// 顶部菜单
	TYPE_TOP_MENU uint8 = 22
)

// 权限类型
// 实现EnumInerface接口
type Type struct {
	enum.Enum[uint8]
}

func (e *Type) AllConstAttrs() map[uint8]map[string]any {
	return map[uint8]map[string]any{
		TYPE_NORMAL: {
			"desc":  "常规",
			"sort":  1,
			"color": "#16b777",
		},
		TYPE_SIDEBAR_MENU: {
			"desc":  "侧边栏菜单",
			"sort":  2,
			"color": "#16baaa",
			"menuLayout": func(html string) string {
				return fmt.Sprintf("<li>%s</li>", html)
			},
			"subMenuLayout": func(html string) string {
				return fmt.Sprintf(`<ul class="sub-menu">%s</ul>`, html)
			},
		},
		TYPE_TOP_MENU: {
			"desc":  "顶部菜单",
			"sort":  3,
			"color": "#1e9fff",
			"menuLayout": func(html string) string {
				return fmt.Sprintf("<li class='top-menu-item'>%s</li>", html)
			},
			"subMenuLayout": func(html string) string {
				return fmt.Sprintf(`<ul class='top-menu-sub'>%s</ul>`, html)
			},
		},
	}
}

// instanceCache 存储已经创建的实例
var typeInstanceCache = make(map[uint8]*Type)

// 根据value获取枚举
func TypeByValue(value uint8) *Type {
	if instance, exists := typeInstanceCache[value]; exists {
		return instance
	}
	e := &Type{}
	enum.SetEnumInstance(&e.Enum, e, value)
	typeInstanceCache[value] = e
	return e
}

var TypeEnum *Type = func() *Type {
	e := &Type{}
	enum.SetEnumInstance(&e.Enum, e)
	return e
}()

// 获取菜单类型的枚举
// 转换为int用于where in ?查询
func GetMenuTypeIntConsts() []int {
	return []int{int(TYPE_SIDEBAR_MENU), int(TYPE_TOP_MENU)}
}

// 获取菜单项结构
func (e *Type) GetMenuLayout(html string) string {
	funRaw := e.GetAttr("menuLayout")
	fun, ok := funRaw.(func(html string) string)
	if !ok {
		return html
	}
	return fun(html)
}

// 获取子菜单项结构
func (e *Type) GetSubMenuLayout(html string) string {
	funRaw := e.GetAttr("subMenuLayout")
	fun, ok := funRaw.(func(html string) string)
	if !ok {
		return html
	}
	return fun(html)
}

// 是否为菜单
func (e *Type) IsMenu() (res bool) {
	return IsMenuType(e.Value)
}

// 是否为菜单类型
func IsMenuType(typ uint8) (res bool) {
	if typ == TYPE_SIDEBAR_MENU || typ == TYPE_TOP_MENU {
		res = true
	}
	return
}
